/**
 * File: BucketNodeIdWriterProcessor.java
 * Created by: mhaimel
 * Created on: May 21, 2010
 * CVS:  $Id: BucketNodeIdWriterProcessor.java 1.0 May 21, 2010 2:29:08 PM mhaimel Exp $
 */
package uk.ac.ebi.curtain.processor.general;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import uk.ac.ebi.curtain.controller.BucketNodeInfoBean;
import uk.ac.ebi.curtain.processor.AbstractQueueProcessor;
import uk.ac.ebi.curtain.util.FileHelper;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.concurrent.CurtainAtomicLongArray;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;
import uk.ac.ebi.velvet.model.Supercontig;

/**
 * @author mhaimel
 *
 */
public class BucketNodeIdWriterProcessor extends AbstractQueueProcessor<BucketNodeInfoBean, File> {

	@Override
	protected File buildReturnObject() {
		return null;
	}

	@Override
	protected File doProcess(BucketNodeInfoBean input) {
		int bucketId = input.getBucketId();
		CurtainAtomicLongArray ctgList = input.getCtgList();
		CurtainAtomicLongArray nodeList = input.getNodeList();
		CurtainAtomicLongArray arcList = input.getArcList();
		
		File base = getContext().currentFiles().getBucketDir();
		File bDir = FileHelper.getSubDirectory(base, bucketId );

		File arcIdFile = Supercontig.getArcIdOutputFile(bDir);
		File ctgFile = Supercontig.getContigIdOutputFile(bDir);
		File nodeFile = Supercontig.getNodeIdOutputFile(bDir);
		bDir.mkdirs();
		persist(arcList, arcIdFile);
		persist(ctgList, ctgFile);
		persist(nodeList, nodeFile);
		return bDir;
	}

	private void persist(CurtainAtomicLongArray ctgList, File ctgFile) {
		PrintWriter out = null;
		try {
			out = new FileIO(ctgFile,false).getPrintWriter();
			int length = ctgList.length();
			for(int i = 0; i < length; ++i){
				long nid = ctgList.get(i);
				out.println(Long.toString(nid));
			}			
		} catch (IOException e) {
			throw new CurtainUncheckedException("Problems writing " + ctgFile,e);
		}finally{
			FileIO.closeQuietly(out);
		}
	}
	
}







